package com.baidu.springcloud.controller;

import com.baidu.springcloud.bean.Payment;
import com.baidu.springcloud.common.CommonResult;
import com.baidu.springcloud.resultenum.ResultEnum;
import com.baidu.springcloud.service.PaymentService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * @author ShiLei
 * @version v1.0
 * @date 2020-03-11 10:57
 */
@RestController
@RequestMapping("api/payment")
@CrossOrigin
@Slf4j
public class PaymentController {

    @Resource
    private PaymentService paymentService;

    @Resource
    private DiscoveryClient discoveryClient;

    @Value("${server.port}")
    private String serverPort;

    @PostMapping("save")
    public CommonResult save(@RequestBody Payment payment) {
        int i = paymentService.savePayment(payment);
        if (i > 0) {
            return new CommonResult<>(ResultEnum.SUCCESS_RESULT.getCode(), ResultEnum.SUCCESS_RESULT.getMessage());
        }
        return new CommonResult<>(ResultEnum.ERROR_RESULT.getCode(), ResultEnum.ERROR_RESULT.getMessage(), serverPort);
    }

    @GetMapping("getPaymentById/{id}")
    public CommonResult getPaymentById(@PathVariable("id") Long id) {
        Payment paymentById = paymentService.getPaymentById(id);
        return new CommonResult<>(ResultEnum.SUCCESS_RESULT.getCode(), ResultEnum.SUCCESS_RESULT.getMessage() + serverPort, paymentById);
    }

    /**
     * 服务发现
     * 获取Eureka服务注册中心下的服务名称端口 url ip地址
     *
     * @return 返回数据实例
     */
    @GetMapping(value = "discovery")
    public Object discovery() {
        //获取服务注册中心下有多少服务数量 以及名称
        List<String> services = discoveryClient.getServices();
        for (String service : services) {
            log.info("*********: " + service);
        }
        //获取eureka注册中心下的某个服务名称实例对象有几个 具体详细信息
        List<ServiceInstance> instances = discoveryClient.getInstances("CLOUD-PAYMENT-SERVICE");
        for (ServiceInstance instance : instances) {
            log.info(instance.getServiceId() + "\t" + instance.getHost() + "\t" + instance.getPort() + "\t" + instance.getUri());
        }
        return this.discoveryClient;
    }

    @GetMapping("lb")
    public String getPaymentLb() {
        return serverPort;
    }

    /**
     * 用来演示feign远程调用超时控制
     *
     * @return
     */
    @GetMapping(value = "payment/feign/timeout")
    public String timeout() {
        try {
            TimeUnit.SECONDS.sleep(3);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return serverPort;
    }

    @GetMapping("zipkin")
    public String zipkin() {
        return serverPort + "O(∩_∩)O";
    }
}
